package com.bianmaba.spring.security.basic.handler;

import com.bianmaba.spring.security.util.ResponseUtil;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: bianmaba-web-framework-extends
 * @description:
 * @author: Chenjiabin
 * @create: 2018-04-22 20:29
 **/
@ConditionalOnMissingBean({BianmabaAccessDeniedHandler.class})
public class BianmabaAccessDeniedHandler extends AccessDeniedHandlerImpl {
    private static final Logger LOGGER = LoggerFactory.getLogger(BianmabaSessionInformationExpiredStrategy.class);

    /**
     * 处理无授权时的错误信息
     *
     * @param request
     * @param response
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        String requestType = request.getHeader("request_type");
        if ("ajax".equals(requestType)) {
            Map<String, Object> result = new HashMap<String, Object>(0);
            result.put("success", false);
            result.put("status", 403);
            result.put("statusText", e.getLocalizedMessage());
            result.put("securityMessage", true);
            result.put("result", "资源请求失败，当前用户没有取得该资源的授权，请联系管理员授权！");
            result.put("exception", ExceptionUtils.getStackTrace(e));
            result.put("failureType", e.getClass().getSimpleName());
            ResponseUtil.writeJson(response, result, 403);
            LOGGER.error(result.get("result").toString(), e);
        } else {
            super.handle(request, response, e);
        }
    }
}
